package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.constants.SystemConstants;
import com.hmdp.constants.RedisConstants;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;


import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import static com.hmdp.constants.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.constants.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
   @Resource
   private IFollowService followService;

    // 定时任务，每分钟运行
    @Scheduled(cron = "0 0/1 * * * ?")
    private void saveBlogLiked2database(){
        //1、获取所有blog的id
        List<Blog> blogList = getBaseMapper().selectList(null);
        blogList.forEach(blog ->{
            //2、在redis中查找每个blog的点赞数
            Boolean hasKey = stringRedisTemplate.hasKey(BLOG_LIKED_KEY + blog.getId());
            if(BooleanUtil.isTrue(hasKey)){
                Long likeNum = stringRedisTemplate.opsForZSet().size(BLOG_LIKED_KEY + blog.getId());
                //3、更新点赞数到数据库
                if(likeNum>0)
                    update().eq("id", blog.getId()).set("liked", likeNum);
            }
        });
    }
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query().orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach( blog -> {
            queryUserByBlog(blog);
            isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(long id) {
        Blog blog = getById(id);
        if(blog==null)
            return Result.fail("博客不存在");
        Boolean hasKey = stringRedisTemplate.hasKey(BLOG_LIKED_KEY + id);
        if(BooleanUtil.isTrue(hasKey)){
            Long likeCount = stringRedisTemplate.opsForZSet().size(BLOG_LIKED_KEY + id);
            if(likeCount!=null) //避免Zset还没建立就查询
                blog.setLiked(Math.toIntExact(likeCount));
        }
        queryUserByBlog(blog);
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        String key = BLOG_LIKED_KEY + blog.getId();
        UserDTO userDTO = UserHolder.getUser();
        if(userDTO == null) return;
        Boolean hasKey = stringRedisTemplate.hasKey(key);
        if(BooleanUtil.isTrue(hasKey)) {
            Double score = stringRedisTemplate.opsForZSet().score(key, userDTO.getId().toString());
            blog.setIsLike(score!=null);
        }
    }

    @Override
    public Result likeBlog(Long id) {
        String key = BLOG_LIKED_KEY+id;
        Long userId = UserHolder.getUser().getId();
        // 判断当前用户是否点赞过
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if(score!=null){
            // 已经点赞
            stringRedisTemplate.opsForZSet().remove(key, userId.toString());
        }else{
            // 注意ZSet用于排序，需要额外传入一个score参数
            stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(long id) {
        String key = BLOG_LIKED_KEY+id;
        // 1、获得Redis中维护的zset内容，即用户id集合(取前5个）
        Set<String> userIdList = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(userIdList==null || userIdList.isEmpty())
            return Result.ok(Collections.emptyList());
        // 2、通过用户id查询用户的信息
        List<Long> ids = userIdList.stream().map(Long::valueOf).collect(Collectors.toList());
        String idListStr = StrUtil.join(",", ids);
        List<UserDTO> userDtoList = userService.query().in("id", ids).last("ORDER BY FIELD(id," + idListStr +")")
                .list().stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDtoList);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        save(blog);
        // 1、查找当前用户的粉丝
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        // 2、将blog的id推送到粉丝的收件箱
        follows.forEach(
            follow -> {
                stringRedisTemplate.opsForZSet().add(FEED_KEY+follow.getUserId(), blog.getId().toString(), System.currentTimeMillis());
            }
        );
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long lastId, Integer offset) {
        Long userId = UserHolder.getUser().getId();
        //1、从Redis的收件箱中查询博客id
        // ZREVRANGEBYSCORE key Max Min LIMIT offset count
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(FEED_KEY + userId, 0, lastId, offset, 2);
        if(typedTuples==null||typedTuples.isEmpty()){
             return Result.ok();
        }
        //2、解析获得的数据
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int ofset = 1;
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            String idStr = typedTuple.getValue();
            ids.add(Long.valueOf(idStr));
            long time = typedTuple.getScore().longValue();
            if(time == minTime){
                ofset+=1;
            }else{
                minTime = time;
                ofset=1;
            }
        }
        //3、从数据库中查询博客的具体信息
        String idStrs = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idStrs + ")")
                .list();
        blogs.forEach(blog->{
            queryUserByBlog(blog);
            isBlogLiked(blog);
        });
        // 4、封装并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(ofset);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }

    private void queryUserByBlog(Blog blog){
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
